import {IGetSelfElementsIdListOptions, IGetTargetParentElementOptions} from "../../types";

// 获取元素节点id， 统计元素本身所以子节点id
export function getSelfElementsIdList(options: IGetSelfElementsIdListOptions){
    const el = options?.el;
    let currentNode = options?.currentNode;

    if(!el.elementIdList) el.elementIdList = [];
    if(!el.elementIdList.includes(currentNode.uid)) el.elementIdList.push(currentNode.uid);
    // 判断字节的
    if(currentNode.childNodes.length){
        for(let childNode of currentNode.childNodes) {
            getSelfElementsIdList({el: el, currentNode: childNode});
        }
    }
    return el;
}

// 获取当前所在页面顶级元素 TaroElement
export function getTargetParentElement(options: IGetTargetParentElementOptions) {
    const el = options?.el;
    let currentNode = options?.currentNode;
    const nodeName = options?.nodeName || 'root';
    const parentNodePropName = options?.parentNodePropName;
    const parentNodePropValue = options?.parentNodePropValue;
    // 若有传入父级元素节点相关参数 parentNodePropName、parentNodePropValue
    if(parentNodePropName && parentNodePropValue) {
        while(currentNode && currentNode.props[parentNodePropName] !== parentNodePropValue){
            if(currentNode.parentNode){
                currentNode = currentNode.parentNode;
            }
        }
        if(currentNode) {
            el.targetParentNode = currentNode;
        }
    } else {
        // TaroElement虚拟节点
        // nodeName: root > block > container > body > html > #document
        // tagName: ROOT > BLOCK > CONTAINER > BODY > HTML > #DOCUMENT
        while (currentNode && currentNode.nodeName !== nodeName) {
            if (currentNode.parentNode) {
                currentNode = currentNode.parentNode;
            }
            // 当nodeName为 'root‘时
            // 默认目标父级元素节点，taro小程序对应<page></page>元素节点，当前页面实际顶级父级元素节点为其字节的
            if(currentNode.parentNode.nodeName === nodeName && 'root' === nodeName) {
                el.targetParentEventNode = currentNode;
            }
        }
        if(currentNode) {
            el.targetParentNode = currentNode;
        }
    }
    return el;
}
